<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\ocean;

use app\command\BaseWork;
use app\enum\CommonEnum;
use app\enum\OeInvalidVideoEnum;
use app\model\OeInvalidVideoModel;
use app\model\OeInvalidVideoScheduleModel;
use app\service\client\AccountService;
use app\service\ocean\MaterialService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class InvalidVideoCleanupTaskBatchWork extends BaseWork
{
    public const SCHEDULE_BATCH_LIST_KEY = 'schedule_oe_invalid_video_batch';

    protected function configure()
    {
        // 指令配置
        $this->setName('oe_invalid_video_cleanup_task_batch_work');
        // 设置参数
        $this->setDescription('批量执行清理巨量无效素材任务');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $this->getOutputMessage('批量执行清理巨量无效素材任务开始');
        $redis = Cache::store('redis')->handler();
        $runTime = time() + 5 * 60;

        while (time() < $runTime) {
            $id = $redis->lpop(self::SCHEDULE_BATCH_LIST_KEY);
            if (! $id) {
                sleep(rand(5, 10));
                continue;
            }

            $obj = (new OeInvalidVideoScheduleModel())->where('id', $id)->field(true)->find();
            if (! $obj instanceof OeInvalidVideoScheduleModel || ! $obj->getKey()) {
                $this->getOutputMessage('任务[' . $id . ']信息获取失败');
                continue;
            }

            $materialIds = [];
            foreach (json_decode($obj->getAttr('material_id'), true) as $mat) {
                $materialIds[] = intval($mat);
            }

            if (empty($materialIds)) {
                $this->getOutputMessage('任务[' . $id . ']无对应素材');
                continue;
            }

            $token = AccountService::getToken(CommonEnum::OE_MEDIA, $obj->getAttr('advertiser_id'));
            if (! $token) {
                $this->getOutputMessage('获取广告主账户[' . $obj->getAttr('advertiser_id') . ']token失败');
                $redis->rPush(self::SCHEDULE_BATCH_LIST_KEY, $id);
                continue;
            }

            $headers = [
                'Access-Token' => $token,
                'Content-Type' => 'application/json',
            ];

            $params = [
                'advertiser_id' => intval($obj->getAttr('advertiser_id')),
                'material_ids' => $materialIds,
            ];

            $isCleared = true;
            $res = MaterialService::setVideoPause($headers, $params);
            if (! $res) {
                $isCleared = false;
            }
            $content = (new OeInvalidVideoModel())->where([
                'advertiser_id' => $obj->getAttr('advertiser_id'),
                'material_id' => $materialIds[0],
                'data_ym' => $obj->getAttr('data_ym'),
            ])->field('id,close_status')->find();
            if (! $content instanceof OeInvalidVideoModel || ! $content->getKey()) {
                $this->getOutputMessage('广告主账户[' . $obj->getAttr('advertiser_id') . ']下素材[' . $materialIds[0] . ']年月[' . $obj->getAttr('data_ym') . ']记录未找到');
                continue;
            }
            if ($content->getAttr('close_status') != OeInvalidVideoEnum::CLOSE_STATUS_SCHEDULE) {
                $this->getOutputMessage('广告主账户[' . $obj->getAttr('advertiser_id') . ']下素材[' . $materialIds[0] . ']年月[' . $obj->getAttr('data_ym') . ']记录非可更新状态');
                continue;
            }

            $content->setAttrs([
                'close_status' => $isCleared ? OeInvalidVideoEnum::CLOSE_STATUS_SUCCESS : OeInvalidVideoEnum::CLOSE_STATUS_FAIL,
                'close_fail_reason' => $isCleared ? null : MaterialService::getError(0),
                'close_datetime' => time(),
                'step_batch_status' => $isCleared ? OeInvalidVideoEnum::CLOSE_STATUS_SUCCESS : OeInvalidVideoEnum::CLOSE_STATUS_FAIL,
            ]);
            if (! $content->save()) {
                $this->getOutputMessage('任务[' . $id . ']更新无效素材关停状态失败');
            }
            $this->getOutputMessage('任务[' . $id . ']批量关停完成');
        }
        $this->getOutputMessage('批量执行清理巨量无效素材任务结束');
    }
}
